package com.lanou3g.hw0517;


import com.lanou3g.hw0517.common.Constant;
import com.lanou3g.hw0517.controller.Controller;
import com.lanou3g.hw0517.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(name = "loginServlet", urlPatterns = "/login")
public class loginServlet extends HttpServlet {
    private Controller controller = new Controller();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String ses = request.getParameter("sess");
        //校验
        String msg = "";
        String msg1 = "";
        User user = controller.login(username, password);
        if (user != null) {
            //登陆成功
            msg = "登陆成功";

            //把user存入session之前,把对象中的密码置空
            user.setPwd("");
            //把用户信息存到session中去
            //获取session对象
            HttpSession session = request.getSession();
            //把用户信息存到session中,注意:晚上可以把User对象,直接存入session
            session.setAttribute(Constant.Session.USER, user);
            request.setAttribute("msg", msg);
            request.getRequestDispatcher("/user/success.jsp").forward(request, response);
            //一周免登陆
            if (ses.equals("ss")) {
                String sessionID = session.getId();
                Cookie cookie = new Cookie("JSESSIONID", sessionID);
                cookie.setMaxAge(7 * 24 * 3600);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        } else {
            //登录失败
            msg = "登录失败";
            msg1 = request.getContextPath() + "/user/login.jsp";
            request.setAttribute("msg", msg);
            request.setAttribute("msg1", msg1);
            request.getRequestDispatcher("/user/msg.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
